package com.bjb.vr.server.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjb.vr.common.ao.SyncDataAo;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.constant.UpgradeConstants;
import com.bjb.vr.common.dto.ExecutedSql;
import com.bjb.vr.common.dto.SyncData;
import com.bjb.vr.common.dto.SysUpgrade;
import com.bjb.vr.common.mapper.ExecutedSqlMapper;
import com.bjb.vr.common.mapper.SyncDataMapper;
import com.bjb.vr.common.mapper.SyncTenantMapper;
import com.bjb.vr.common.mapper.SysUpgradeMapper;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/7/13 12:26
 */
@Slf4j
@Service
public class DataHandlerService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private SyncDataMapper syncDataMapper;

    @Resource
    private ExecutedSqlMapper executedSqlMapper;

    @Resource
    private SyncTenantMapper tenantMapper;

    @Resource
    private SysUpgradeMapper upgradeMapper;


    /**
     * 同步数据到数据库
     *
     * @param syncDataAo
     */
    public void sendSyncData(SyncDataAo syncDataAo) {
        if (StringUtils.isBlank(syncDataAo.getStatement())) {
            return;
        }

        try {
            // 执行传入过来的SQL语句
            jdbcTemplate.execute(syncDataAo.getStatement());
            log.info("【客户端-->服务端】: " + syncDataAo.getStatement());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 查询数据给本地
     *
     * @param syncDataAo
     * @return
     */
    public List queryCloudData(SyncDataAo syncDataAo) {
        log.debug("获取租户[{}}]的同步数据", syncDataAo.getTenantId());
        // 放行SQL拦截,允许通过
        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);
        LambdaQueryWrapper<SyncData> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(StringUtils.isNotBlank(syncDataAo.getTenantId()), SyncData::getTenantId, syncDataAo.getTenantId());
        queryWrapper.orderByAsc(SyncData::getId);
        Page page = syncDataMapper.selectPage(new Page<>(0, 10), queryWrapper);
        List<SyncData> records = page.getRecords();
        return records;
    }

    /**
     * 删除同步完成之后的数据
     *
     * @param syncDataAo
     * @return
     */
    public boolean removeSyncData(SyncDataAo syncDataAo) {
        // 放行SQL拦截,允许通过
        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);
        try {
            String[] removeIds = syncDataAo.getRemoveIds().split(",");
            int result = syncDataMapper.deleteBatchIds(Arrays.asList(removeIds));
            String[] removeMd5s = syncDataAo.getRemoveMd5s().split(",");
            LambdaQueryWrapper<ExecutedSql> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(ExecutedSql::getMd5, removeMd5s);
            executedSqlMapper.delete(queryWrapper);
            log.debug("[云端]成功删除【{}】条同步数据！", result);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 获取需要升级的数据
     *
     * @param syncDataAo
     * @return
     */
    public List<SysUpgrade> getUpgradeInfo(SyncDataAo syncDataAo) {
        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);
        String zipLatestVersion = upgradeMapper.queryLatestVersion(UpgradeConstants.ZIP, syncDataAo.getTenantId());
        String apkLatestVersion = upgradeMapper.queryLatestVersion(UpgradeConstants.APK, syncDataAo.getTenantId());
        ArrayList<String> versions = new ArrayList<>();
        versions.add(zipLatestVersion);
        versions.add(apkLatestVersion);
        versions.removeAll(Collections.singleton(null));
        List<SysUpgrade> upgradeList = upgradeMapper.selectUpgradeInfo(versions, syncDataAo.getTenantId());
        return upgradeList;
    }
}
